
/**
 * 封装ajax工具函数
 * 
 * options = {
 *     method:'get',
 *     url:'http://10.7.176.87:8088/api/list',
 *     data:{
 *         username:'admin',
 *         password:123
 *     },
 *     success:function(data){
 *         //处理成功
 *     },
 *     error:function(error){
 *         //处理失败
 *     }
 *
 * }
 * 
 *  ajax(options)  使用ajax工具函索进行网络请求
 * 
 */

function ajaxPromise(obj) {
    const promise = new Promise(function (resolve, reject) {
        ///封装ajax异步任务
        ajax({
            method: obj.method,
            url: obj.url,
            data: obj.data,
            success: function (data) {
                resolve(data)
            },
            error: function (error) {
                reject(error)
            }
        })
    })
    return promise
}

function ajax(options) {
    //1创建XMLHttpRequest对象
    const xhr = new window.XMLHttpRequest

    //2处理参数，将对象参数转成名称值对
    let parame = formataParame(options.data)   
    
    let method = options.method.toUpperCase()
    if (method == 'GET') {
        xhr.open(method, options.url + '?' + parame)
        xhr.send()
    } else if (method == 'POST') {
        xhr.open(method, options.url)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        xhr.send(parame)
    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                let result = xhr.responseText
                let data = JSON.parse(result)
                options.success(data)
            } else {
                options.error(xhr)
            }
        }
    }
}

/**
 *     {
 *         username:'admin',
 *         password:123                 =>   username='admin'&password=1234
 *     }
 * @param {*} obj 
 */
function formataParame(obj) {//将参数转成名称值队的工具函数
    let arr = []
    for (let key in obj) {
        let item = `${key}=${obj[key]}`
        
        arr.push(item)
    }

    let str = arr.join('&')
    return str
    
}